<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';

import { onBeforeMount, ref, markRaw } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message, Switch, Input, Tag, Cascader } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getMaterialBatchBillList,
  exportMaterialBatchBill,
  updateBatchOrder,
  getCategoryOptions,
  getTimeCategoryOptions,
  getMerchandiserOptions,
  getMaterialTypeOptions,
  getFactoryOptions, getMaterialBatchBillList2,
} from '#/api/materialBatchBill';
import { useDebounceFn } from '@vueuse/core';
import dayjs from 'dayjs';
import { useRoute } from 'vue-router';

import TwoFields from '../modules/two-fields.vue';

const formData = ref<any>({});
// 关键字和加载状态
const keyword = ref({
  merchandiser: '',
  material_type: '',
  factory: '',
  supply_id: '',
});

const { SHOW_CHILD } = Cascader;

interface RowType {
  [key: string]: any;
}

const route = useRoute();
const selectedRows = ref<RowType[]>([]);
const loading = ref(false);
const params = ref<any>({ quick_search: '' });
const isInit = ref(false);

// 初始化时获取商品分类和时间分类选项
onBeforeMount(() => {
  fetchCategoryOptions();
  fetchTimeCategoryOptions();
});

// 获取商品分类选项
const fetchCategoryOptions = async () => {
  try {
    const { list } = await getCategoryOptions();
    // 动态更新formApi中的category选项
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          componentProps: {
            options: list || [],
            // showCheckedStrategy: SHOW_CHILD,
            // maxTagCount: 'responsive',
            // onChange: (value: any[]) => {
            //   // 点击父级时自动选中所有子级，输出分层级数组
            //   console.log('Cascader value:', value)
            // },
          },
          fieldName: 'category',
        },
      ]);
    }
  } catch (error) {
    console.error('获取商品分类选项失败:', error);
    return [];
  }
};

// 获取时间分类选项
const fetchTimeCategoryOptions = async () => {
  try {
    const { list } = await getTimeCategoryOptions();
    // 动态更新formApi中的time_category选项
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          componentProps: {
            options: list || [],
            // showCheckedStrategy: SHOW_CHILD,
            // maxTagCount: 'responsive',
            // onChange: (value: any[]) => {
            //   // 点击父级时自动选中所有子级，输出分层级数组
            //   console.log('Cascader value:', value)
            // },
          },
          fieldName: 'time_category',
        },
      ]);
    }
  } catch (error) {
    console.error('获取时间分类选项失败:', error);
    return [];
  }
};

// 获取跟单人选项
const fetchMerchandiserOptions = async ({
  keyword = '',
}: Record<string, any> = {}) => {
  try {
    const { list } = await getMerchandiserOptions({
      quick_search: keyword,
      page: 1,
      limit: 100,
      key: 'merchUsers',
      initKey: 'data_value',
      initValue: keyword ? '' : formData.value?.merchandiser,
      select: true,
    });

    return list.map((item: any) => ({
      label: item.data_value,
      value: item.data_value,
    }));
  } catch (error) {
    console.error('获取跟单人选项失败:', error);
    return [];
  }
};

// 获取物料类型选项
const fetchMaterialTypeOptions = async ({
  keyword = '',
}: Record<string, any>) => {
  try {
    const { list } = await getMaterialTypeOptions({
      quick_search: keyword,
      page: 1,
      limit: 30,
      initKey: 'id',
      initValue: keyword ? '' : formData.value?.material_type,
      select: true,
    });
    return list.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
  } catch (error) {
    console.error('获取物料类型选项失败:', error);
    return [];
  }
};

// 获取加工厂选项
const fetchFactoryOptions = async ({ keyword = '' }: Record<string, any>) => {
  try {
    const { list } = await getFactoryOptions({ quick_search: keyword });
    return list.map((item: any) => ({
      label: item.SupplyNa,
      value: item.id,
    }));
  } catch (error) {
    console.error('获取加工厂选项失败:', error);
    return [];
  }
};

// 表单配置
const createSchema = () => [
  {
    component: 'Cascader',
    fieldName: 'category',
    label: '货品分类',
    operator: '123',
    render: 'customRender',
    componentProps: {
      options: [],
      allowClear: true,
      multiple: true,
      showSearch: true,
      alwaysLoad: true,
      showCheckedStrategy: SHOW_CHILD,
      maxTagCount: 'responsive',
      // maxTagCount 设为 'responsive' 时，当标签过多时会自动折叠显示，并在鼠标悬停时显示 tooltip
    },
  },
  {
    component: 'Cascader',
    fieldName: 'time_category',
    label: '时间分类',
    operator: '123',
    componentProps: {
      options: [],
      allowClear: true,
      multiple: true,
      showSearch: true,
      alwaysLoad: true,
      showCheckedStrategy: SHOW_CHILD,
      maxTagCount: 'responsive',
      // maxTagCount 设为 'responsive' 时，当标签过多时会自动折叠显示，并在鼠标悬停时显示 tooltip
    },
  },
  {
    component: 'Input',
    fieldName: 't*template_no',
    label: '简码',
    operator: 'LIKE',
    componentProps: {
      allowClear: true,
      placeholder: '模糊搜索',
    },
  },
  {
    component: 'Input',
    fieldName: 'g*goods_no',
    label: '货号',
    operator: '=',
    defaultValue: route.query.goods_no || undefined,
    componentProps: {
      allowClear: true,
      placeholder: '等值搜索',
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'g*merchandiser',
    label: '跟单人',
    operator: 'IN',
    componentProps: () => ({
      api: fetchMerchandiserOptions,
      // filterOption: false,
      onSearch: useDebounceFn((value: string) => {
        keyword.value.merchandiser = value;
      }, 300),
      // params: {
      //   keyword: keyword.value.merchandiser || undefined,
      // },
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
      mode: 'multiple',
      immediate: false,
      // alwaysLoad: true,
      visibleEvent: 'onFocus',
      // onDropdownVisibleChange: (open: boolean) => {
      //   keyword.value.merchandiser = ''
      // },
    }),
  },
  {
    component: 'Input',
    fieldName: 'gp*goods_purchase_sn',
    label: '大货采购单号',
    operator: '=',
    defaultValue: route.query.goods_purchase_sn || undefined,
    componentProps: {
      allowClear: true,
      placeholder: '等值搜索',
    },
  },
  {
    component: 'Select',
    fieldName: 't*data_type',
    label: '系统人员分类',
    operator: 'IN',
    componentProps: {
      options: [
        { label: '外套', value: '1' },
        { label: '内搭', value: '2' },
        { label: '裤子', value: '3' },
        { label: '毛衣', value: '4' },
      ],
      multiple: true,
      allowClear: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'gexing',
    label: '个性筛选',
    operator: '123',
    componentProps: {
      options: [
        { label: '应提供物料', value: '应提供物料' },
        { label: '显示未下单过', value: '应下单' },
        { label: '显示应发料', value: '应发料' },
        { label: '裁床后存在下单差异', value: '裁床后存在下单差异' },
        { label: '裁床后存在发料差异', value: '裁床后存在发料差异' },
      ],
      // multiple: true,
      allowClear: true,
    },
  },
  {
      component: 'ApiSelect',
      fieldName: 'm*supply_id',
      label: '物料供应商',
      operator: 'IN',
      componentProps: () => ({
        api: fetchFactoryOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supply_id = value
        }, 300),
        params: { keyword: keyword.value.supply_id || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        maxTagCount: 'responsive',
        mode: 'multiple',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          console.log('visible', open)
          if (open) keyword.value.supply_id = ''
        },
      }),
    },
  {
    component: 'Input',
    fieldName: 'purchase_num*caigou_ids',
    label: '物料采购单号',
    operator: 'FIND_IN_SET',
    componentProps: {
      allowClear: true,
      placeholder: '等值搜索',
    },
  },
  {
    component: 'Input',
    fieldName: 'sbm*bom_name',
    label: 'bom类型',
    operator: 'LIKE',
    componentProps: {
      allowClear: true,
      placeholder: '模糊搜索',
    },
  },
  {
    component: 'Input',
    fieldName: 'm*material_name',
    label: '物料名称',
    operator: 'LIKE',
    componentProps: {
      allowClear: true,
      placeholder: '模糊搜索',
    },
  },
  {
    component: 'Input',
    fieldName: 'ms*sku_sn',
    label: '物料编号',
    operator: 'LIKE',
    componentProps: {
      allowClear: true,
      placeholder: '模糊搜索',
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'm*material_type',
    label: '物料类型',
    operator: 'IN',
    componentProps: () => ({
      api: fetchMaterialTypeOptions,
      // filterOption: false,
      // onSearch: useDebounceFn((value: string) => {
      //   keyword.value.material_type = value
      // }, 300),
      // params: {
      //   keyword: keyword.value.material_type || undefined,
      // },
      allowClear: true,
      showSearch: true,
      optionFilterProp: 'label',
      mode: 'multiple',
      immediate: false,
      // alwaysLoad: true,
      visibleEvent: 'onFocus',
      // onDropdownVisibleChange: (open: boolean) => {
      //   keyword.value.material_type = ''
      // },
    }),
  },
  {
    component: 'RangePicker',
    fieldName: 'gp*purchase_date',
    label: '下单日期',
    operator: 'RANGE',
    render: 'datetime',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
  },

  {
    component: 'RangePicker',
    fieldName: 'm*created_at',
    label: '物料提供日期',
    operator: 'RANGE',
    render: 'datetime',
    componentProps: {
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'gp*supply_id',
    label: '加工厂',
    operator: 'IN',
    componentProps: () => ({
      api: fetchFactoryOptions,
      filterOption: false,
      onSearch: useDebounceFn((value: string) => {
        keyword.value.factory = value;
      }, 300),
      params: { keyword: keyword.value.factory || undefined },
      mode: 'multiple',
      // remote: true,
      allowClear: true,
      showSearch: true,
      immediate: false,
      alwaysLoad: true,
      maxTagCount: 'responsive',
      visibleEvent: 'onFocus',
      placeholder: '加工厂',
      onDropdownVisibleChange: (open: boolean) => {
        keyword.value.factory = '';
      },
    }),
  },
  // {
  //   component: markRaw(TwoFields),
  //   fieldName: 'purchase_num*unused_stock',
  //   disabledOnChangeListener: false,
  //   label: '未使用库存',
  //   operator: 'RANGE',
  //   valueToString: true,
  //   componentProps: {
  //     allowClear: true,
  //     placeholder: '范围筛选',
  //   },
  // },
];

const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: createSchema(),
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
};

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
   checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    //  isCurrent: true,
    isHover: true,
  },
  columnConfig: { useKey: true },
  columns: [
    { type: 'checkbox', width: 50 },
    {
      title: '货品信息',
      field: 'goods_info',
      align: 'center',
      children: [
        {
          field: 'template_no',
          title: '简码',
          width: 90,
          align: 'center',
        },
        {
          field: 'goods_no',
          title: '货号',
          width: 90,
          align: 'center',
        },
        {
          field: 'goods_color_name',
          title: '货品颜色',
          width: 100,
          align: 'center',
        },
      ],
    },
    {
      title: '采购信息',
      field: 'purchase_info',
      align: 'center',
      children: [
        {
          field: 'batch_create_time',
          title: '下单日期',
          width: 100,
          align: 'center',
          formatter: ({ cellValue }) => {
            if (cellValue) {
              return dayjs(cellValue).format('YYYY-MM-DD');
            }
            return '-';
          },
        },
        {
          field: 'batch_name',
          title: '采购性质',
          width: 80,
          align: 'center',
        },
        {
          field: 'factory_name',
          title: '供应商',
          width: 90,
          align: 'center',
        },
        {
          field: 'goods_purchase_sn',
          title: '采购单号',
          width: 120,
          align: 'center',
        },
        {
          field: 'product_sn',
          title: '生产制单号',
          width: 120,
          align: 'center',
        },
      ],
    },
    {
      title: '物料实际面料',
      field: 'material_info',
      align: 'center',
      children: [
        {
          field: 'exp_loss',
          title: '导出损耗率',
          width: 100,
          align: 'center',
        },
        {
          field: 'material_code',
          title: '物料编号',
          width: 120,
          align: 'center',
        },
        {
          field: 'sku_sn',
          title: 'sku编号',
          width: 120,
          align: 'center',
        },
        {
          field: 'material_name',
          title: '物料名称',
          width: 200,
          align: 'center',
        },
        {
          field: 'SupplyNa',
          title: '供应商',
          width: 80,
          align: 'center',
        },
        {
          field: 'price',
          title: '单价',
          width: 60,
          align: 'center',
        },
        {
          field: 'unit',
          title: '单位',
          width: 50,
          align: 'center',
        },
      ],
    },
    {
      field: 'order_quantity',
      title: '订单件数',
      width: 80,
      align: 'center',
    },
    {
      field: 'cuted_num',
      title: '裁床数',
      width: 70,
      align: 'center',
    },
    {
      field: 'need_num',
      title: '物料需数',
      width: 70,
      align: 'center',
    },
    {
      field: 'caigou_ids',
      title: '物料采购单号',
      width: 120,
      align: 'center',
      slots: { default: 'caigouIds' },
    },
    {
      field: 'purchase_num',
      title: '下单数量',
      width: 80,
      align: 'center',
    },
    {
      field: 'purchase_diff_num',
      title: '下单差异',
      width: 80,
      align: 'center',
      slots: { default: 'purchaseDiff' },
    },
    {
      field: 'reviced_num',
      title: '实收数量',
      width: 80,
      align: 'center',
    },
    {
      field: 'send_num',
      title: '实发数量',
      width: 80,
      align: 'center',
    },
    {
      field: 'send_diff_num',
      title: '实发差异',
      width: 80,
      align: 'center',
      slots: { default: 'sendDiff' },
    },
    {
      field: 'no_send_num',
      title: '未发料',
      width: 70,
      align: 'center',
      slots: { default: 'noSendNum' },
    },
    {
      field: 'pur_ret_total',
      title: '采购退料',
      width: 80,
      align: 'center',
      slots: { default: 'purRetTotal' },
    },
    {
      field: 'unused_stock',
      title: '未使用库存',
      width: 100,
      align: 'center',
      slots: { default: 'unusedStock' },
    },
    {
      field: 'warehouse_name',
      title: '存放仓库',
      width: 140,
      align: 'center',
    },
    {
      field: 'is_factory_supply',
      title: '厂供',
      fixed: 'right',
      slots: { default: 'factorySupply' },
      width: 70,
      align: 'center',
    },
    {
      field: 'not_caigou',
      title: '无需采购',
      fixed: 'right',
      slots: { default: 'notCaigou' },
      width: 70,
      align: 'center',
    },
    {
      field: 'not_fa',
      title: '无需发料',
      fixed: 'right',
      slots: { default: 'notFa' },
      width: 70,
      align: 'center',
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 30 },
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        console.log('formValues', formValues);
        const search = await gridApi.formApi.getFiltersValues(formValues);
        const { list, total } = await getMaterialBatchBillList2({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
        });
        return { items: list, total: total };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'material_batch_bill_list',
  customConfig: {
    storage: true,
  },
};

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords();
    },
  },
});

const debouncedReload = useDebounceFn(gridApi.reload, 1000);

// 处理开关变更
const handleSwitchChange = async (
  row: RowType,
  field: string,
  loadingField: string,
) => {
  if (isInit.value) {
    return;
  }

  row[loadingField] = true;
  try {
    const res = await updateBatchOrder({
      // batch_id: row.goods_purchase_id,
      id: row.id,
      updateData: {
        [field]: row[field],
      },
    });

    message.success('操作成功');
  } catch (error) {
    message.error('操作失败');
    row[field] = !row[field];
  } finally {
    row[loadingField] = false;
  }
};

// 处理导出
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0);
  try {
    const search = await gridApi.formApi.getFiltersValues();
    await exportMaterialBatchBill({
      search,
      is_exp: true,
    });
  } catch (e) {
    message.error('导出失败');
  } finally {
    hide();
  }
};

//// 设置初始默认值已在schema中处理
</script>

<template>
  <Page auto-content-height>
    <Grid :loading="loading">
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleExport"
          >导出数据</Button
        >
      </template>

      <template #toolbar-tools>
        <div class="hidden">
          <Input
            type="text"
            placeholder="请搜索..."
            v-model:value="params.quick_search"
            :allow-clear="true"
            @input="debouncedReload"
          />
        </div>
      </template>

      <template #caigouIds="{ row }">
        <div>{{ row.caigou_ids }}</div>
      </template>

      <template #purchaseDiff="{ row }">
        <span
          :style="{
            color:
              row.not_caigou === 0 && row.purchase_diff_num < 0 ? 'red' : '',
          }"
        >
          {{ row.purchase_diff_num }}
        </span>
      </template>

      <template #sendDiff="{ row }">
        <span
          :style="{
            color: row.not_fa === 0 && row.send_diff_num < 0 ? 'red' : '',
          }"
        >
          {{ row.send_diff_num }}
        </span>
      </template>

      <template #noSendNum="{ row }">
        <span :style="{ color: row.no_send_num > 0 ? 'orange' : '' }">
          {{ row.no_send_num }}
        </span>
      </template>

      <template #purRetTotal="{ row }">
        <span :style="{ color: row.pur_ret_total > 0 ? 'orange' : '' }">
          {{ row.pur_ret_total }}
        </span>
      </template>

      <template #unusedStock="{ row }">
        <span :style="{ color: row.unused_stock > 0 ? 'orange' : '' }">
          {{ row.unused_stock }}
        </span>
      </template>

      <template #factorySupply="{ row }">
        <Switch
          v-model:checked="row.is_factory_supply"
          :loading="row.factorysupply_loading"
          @change="
            handleSwitchChange(
              row,
              'is_factory_supply',
              'factorysupply_loading',
            )
          "
          :checked-children="'是'"
          :un-checked-children="'否'"
        />
      </template>

      <template #notCaigou="{ row }">
        <Switch
          v-model:checked="row.not_caigou"
          :loading="row.notcaigou_loading"
          @change="handleSwitchChange(row, 'not_caigou', 'notcaigou_loading')"
          :checked-children="'是'"
          :un-checked-children="'否'"
        />
      </template>

      <template #notFa="{ row }">
        <Switch
          v-model:checked="row.not_fa"
          :loading="row.notfa_loading"
          @change="handleSwitchChange(row, 'not_fa', 'notfa_loading')"
          :checked-children="'是'"
          :un-checked-children="'否'"
        />
      </template>
    </Grid>
  </Page>
</template>
